let express = require("express")();
const { response } = require("express");
// 下载一个提供静态服务的模块
let expressStatic = require("express-static");
// 引入myspl数据库
let mysql = require('mysql');
// 规划一个数据库链接
let sql = mysql.createConnection({
    host      :'localhost',
    user      :'root',
    password  :'123456',
    database  :'students',
    timezone : "08:00"
});
// 尝试连接
sql.connect();

// 查库，找数据库里的所有东西，并返回给前端
express.get("/getstudentList",(request,response)=>{
	sql.query(`SELECT * FROM students`,(error,data)=>{
		if(error){
			console.log(error)
			response.send("error")
		}
		else{
			response.send(JSON.stringify(data))
		}
	})
})
// 删除
express.get("/deleteStudent",(request,response)=>{
	sql.query(`DELETE FROM students WHERE id=${request.query.id}`,(error,data)=>{
		if(error){
			console.log(error)
			response.send("error")
		}
		else{
			response.send("success")
		}
	})
})

// 添加学生
express.get("/addStudent",(request,response)=>{
	let n = request.query;
	sql.query(`INSERT INTO students (name,age,sex,city,joinDate) VALUES ("${n.name}","${n.age}","${n.sex}","${n.city}","${n.joinDate}")`,(error,data)=>{
		if(error){
			console.log(error)
			response.send("error")
		}
		else{
			response.send("success")
			console.log(`新增学生${n.name}操作成功`)
		}
	})
})

// 编辑
express.get("/editStudent",(request,response)=>{
	let p = request.query;
	sql.query(`UPDATE students SET name="${p.newname}",age="${p.newage}",sex="${p.newsex}",city="${p.city}",joinDate="${p.joinDate}" WHERE id="${p.id}"`,(error,data)=>{
		if(error){
			console.log(error)
			response.send("error")
		}
		else{
			response.send("success")
			console.log(`修改学生${p.newname}成功`)
		}
	})
})


express.use(expressStatic (__dirname+'/static'))
let port = 8080;
// 监听到一个端口上
express.listen(port)